//
//  SLPreferencesSetVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/23.
//

#import "SLPreferencesSetVC.h"
#import "SLPreferencesSetCell.h"
#import "SLLanguageSelectView.h"
#import "SLChangePswdVC.h"
#import "SLPermissionSetVC.h"
#import <UserNotifications/UserNotifications.h>
static  NSString *const kCellId = @"SLPreferencesSetCell";

@interface SLPreferencesSetVC ()<UITableViewDelegate,UITableViewDataSource>{
    UNAuthorizationStatus _pushStatus;
}
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UITableView *tableView;
@end

@implementation SLPreferencesSetVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self updatePushStatus];
    [self setUpSubViews];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePushStatus) name:@"backToApp" object:nil];
}

-(void)updatePushStatus{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        dispatch_main_async_safe(^{
            self->_pushStatus = settings.authorizationStatus;
            [self refreshSubViews];
        });
    }];
}

-(void)setUpSubViews{
    self.title = kLocalString(@"Preferences");
    [self.view addSubview:self.tableView];
}

-(void)confiDatas{
    [self.dataArray removeAllObjects];
//    NSArray *sectionTitle1 = @[kLocalString(@"Language"),kLocalString(@"Change password"),kLocalString(@"Biometric login"),kLocalString(@"Temperature unit")];
    NSArray *sectionTitle1 = @[kLocalString(@"Temperature unit")];
    NSString *curLang = [[NSUserDefaults standardUserDefaults] objectForKey:@"curLang"];
    NSString *langStr = [curLang isEqualToString:@"ar"] ? @"بالعربية" : @"English";
    
    NSString *curTempUnit = kSTRING([[NSUserDefaults standardUserDefaults] objectForKey:@"curTempUnit"]);
    NSString *unitStr = [curTempUnit isEqualToString:@"F"] ? @"°F" : @"°C";
    NSArray *sectionContent1 = @[unitStr];
    
    NSString *pushStr = _pushStatus == UNAuthorizationStatusAuthorized ? kLocalString(@"Allowed"):kLocalString(@"Denied");
    NSArray *sectionTitle2 = @[kLocalString(@"Temperature unit"),kLocalString(@"Permissions"),kLocalString(@"Clear cache"),kLocalString(@"App notifications")];
    NSArray *sectionContent2 = @[unitStr,@"",@"",pushStr];
    
    NSMutableArray *section1 = [NSMutableArray new];
    NSMutableArray *section2 = [NSMutableArray new];
    
    [sectionTitle1 enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *content = sectionContent1[idx];
        NSMutableDictionary *info = [NSMutableDictionary new];
        [info setObject:title forKey:@"title"];
        [info setObject:content forKey:@"content"];
        if ([title isEqualToString:kLocalString(@"Biometric login")]) {
            [info setObject:@"2" forKey:@"type"];
        }else{
            [info setObject:@"1" forKey:@"type"];
        }
        [section1 addObject:info];
    }];
    
    [sectionTitle2 enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *info = [NSMutableDictionary new];
        NSString *content = sectionContent2[idx];
        [info setObject:title forKey:@"title"];
        [info setObject:content forKey:@"content"];
        [info setObject:@"1" forKey:@"type"];
        [section2 addObject:info];
    }];
    
//    [_dataArray addObject:section1];
    [_dataArray addObject:section2];
}

-(void)refreshSubViews{
    [self confiDatas];
    [_tableView reloadData];
}

#pragma mark - ================<tableViewDataSource>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *sectionArr = _dataArray[section];
    return sectionArr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLPreferencesSetCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *info = _dataArray[indexPath.section][indexPath.row];
    NSArray *section = _dataArray[indexPath.section];
    cell.line.hidden = indexPath.row == section.count-1;
    cell.titleLbl.text = info[@"title"];
    cell.contentLbl.text = info[@"content"];
    cell.changeBtn.hidden = [info[@"type"] isEqualToString:@"1"];
    cell.list.hidden = ![info[@"type"] isEqualToString:@"1"];
    [cell.contentView setRoundedCorners:0 forCorners:UIRectCornerAllCorners frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
    if (indexPath.row == section.count-1) {
        [cell.contentView setRoundedCorners:20.0 forCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
    }else if (indexPath.row == 0){
        [cell.contentView setRoundedCorners:20.0 forCorners:UIRectCornerTopLeft | UIRectCornerTopRight frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
    }
    return cell;
}

#pragma mark - ================<UITableViewDelegate>===============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, kScreenWidth, 20);
        headview.contentView.backgroundColor = KClearColor;
    }
    return headview;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        footerView.contentView.backgroundColor = KClearColor;
    }
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *info = _dataArray[indexPath.section][indexPath.row];
    NSString *title = info[@"title"];
    if ([title isEqualToString:kLocalString(@"Language")]) {
        [self showLangSelectView];
    }else if ([title isEqualToString:kLocalString(@"Change password")]){
        SLChangePswdVC *vc = [[SLChangePswdVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:kLocalString(@"Biometric login")]){
        
    }else if ([title isEqualToString:kLocalString(@"Temperature unit")]){
        [self showTemperatureUnitView];
    }else if ([title isEqualToString:kLocalString(@"Permissions")]){
        SLPermissionSetVC *vc = [[SLPermissionSetVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if ([title isEqualToString:kLocalString(@"Clear cache")]){
        [SLTipAlertView showWith:kLocalString(@"Please note") content1:kLocalString(@"Cache is temporary data generated while you use this device, and deleting it won't affect the device's logs and normal operation. Continue to delete?") content2:@"" doneBtn:kLocalString(@"Delete cache") cancelBtn:kLocalString(@"Cancel") action:^(NSInteger index) {
            if (index == 1) {
                [ZCTool showLoadingOnKeyWindow];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [ZCTool hideLoadingOnKeyWindow];
                    [self showSuccessViews];
                });
            }
        }];
        
    }else if ([title isEqualToString:kLocalString(@"App notifications")]){
        [self openNotifySystem];
    }
}

-(void)openNotifySystem{
    
    if (@available(iOS 15.4, *)) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenNotificationSettingsURLString];
        if( [[UIApplication sharedApplication] canOpenURL:url] ) {
            [[UIApplication sharedApplication] openURL:url options:@{}completionHandler:nil];
        }
    } else {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if( [[UIApplication sharedApplication] canOpenURL:url] ) {
            [[UIApplication sharedApplication] openURL:url options:@{}completionHandler:nil];
        }
    }
}


-(void)showSuccessViews{
    __weak SLSuccessAlertView *alert = [SLSuccessAlertView viewFromXIB];
    alert.contentLbl.text = kLocalString(@"App cache has been deleted successfully.");
    [alert setBtnBlock:^(NSInteger btnIndex) {
        [alert removeFromSuperview];
    }];
    [kAppWindow addSubview:alert];
}

-(void)showLangSelectView{
    SLLanguageSelectView *langView = [SLLanguageSelectView viewFromXIB];
    [langView showWithAnmation:self.view];
    kWeakSelf(self);
    [langView setLangChangeBlock:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"langChange" object:nil];
        [weakself refreshSubViews];
    }];
}

-(void)showTemperatureUnitView{
    SLLanguageSelectView *temperatureView = [SLLanguageSelectView viewFromXIB];
    temperatureView.style = 2;
    [self.view addSubview:temperatureView];
    [temperatureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    kWeakSelf(self);
    [temperatureView setLangChangeBlock:^{
        [weakself refreshSubViews];
    }];
}


#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, SafeAreaTopHeight,kScreenWidth-40,kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight) style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 50;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId bundle:nil] forCellReuseIdentifier:kCellId];
        _tableView.backgroundColor = KClearColor;
    }
    return _tableView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}



@end
